# -*- coding: utf-8 -*-
# @File    : captcha.py
# @Author  : Xiewh
# @Email   : 1679860867@qq.com
# @Time    : 2020/11/29 12:58
# @Function:
import io
import json
import time
import base64
import requests
import common.headers as head
from common.api_url import *
from common.api_constant import *
import PIL.Image as Image


def get_captcha(cookie, show=None):
    try:
        headers = head.Captcha
        headers['cookie'] = cookie
        u = url_split(YIBAN_CHROME_HOST, YIBAN_CAPTCHA, 2)
        v = 'v=' + str(int(time.time()))
        r = requests.get(u + '?' + v, headers=headers)
        base64_image = base64.encodebytes(r.content).decode('UTF-8').replace("\n", "")
        if show is not None:
            binary_data = base64.b64decode(base64_image)
            img_data = io.BytesIO(binary_data)
            image = Image.open(img_data)
            image.show()
        return {'code': 1, 'msg': '获取验证码图片成功', 'data': base64_image}
    except Exception as ex:
        return {'code': -1, 'msg': '获取验证码图片失败 ' + str(ex)}


def image_transfer(base64_image, save_file):
    """
    将图片进行降噪处理, 通过二值化去掉后面的背景色并加深文字对比度
    """
    try:
        binary_data = base64.b64decode(base64_image)
        img_data = io.BytesIO(binary_data)
        image = Image.open(img_data)
        threshold = 100  # 该阈值不适合所有验证码，具体阈值请根据验证码情况设置
        img = image.convert("L")  # 转灰度
        pixels = img.load()
        w, h = img.size
        # 根据阈值 threshold , 将所有像素都置为 0(黑色) 或 255(白色), 便于接下来的分割
        for y in range(h):
            for x in range(w):
                if pixels[x, y] < threshold:
                    pixels[x, y] = 0
                else:
                    pixels[x, y] = 255
        img.save(save_file)
        return {'code': 1, 'msg': '操作成功'}
    except Exception as ex:
        return {'code': -1, 'msg': '验证码处理失败 ' + str(ex)}


def appdemo_generalocr(file_path):
    try:
        file = {
            'image_file': ('file', open(file_path, 'rb'), 'image/png')
        }
        OCR_API_URL = 'https://ai.qq.com/cgi-bin/appdemo_generalocr?g_tk='
        ret = json.loads(requests.post(OCR_API_URL, files=file).text)
        if ret['ret'] != 0:
            return {'code': -1, 'msg': '验证码识别失败 ' + ret['msg']}
        if ret['data']['item_list'].__len__() <= 0:
            return {'code': -1, 'msg': '识别结果为空'}
        return {'code': 1, 'msg': '验证码识别成功', 'data': ret['data']['item_list'][0]['itemstring']}
    except Exception as ex:
        return {'code': -1, 'msg': '验证码识别错误 ' + str(ex)}
